package io.kimmking.kmq.core;

import io.kimmking.kmq.demo.Order;
import lombok.Data;

import java.util.concurrent.TimeUnit;

@Data
public final class Queue {

    private int capacity;
    // 当前消费的位置
    private int currentIndex;
    // 最后一条消息位置
    private int lastIndex;
    // 消息数组
    private KmqMessage[] messages;

    // final ReentrantLock lock = new ReentrantLock();
    // private final Condition notEmpty = lock.newCondition();
    // private final Condition notFull = lock.newCondition();

    public Queue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        this.messages = new KmqMessage[capacity];
    }

    public boolean isFull(){
        return lastIndex == capacity-1;
    }

    public boolean isEmpty(){
        return lastIndex == currentIndex;
    }

    public KmqMessage poll(long timeout, TimeUnit unit) {
        if(isEmpty()){
            return null;
        }
        KmqMessage msg = messages[currentIndex];
        currentIndex++;
        return msg;
    }

    public boolean offer(KmqMessage msg) {
        if (isFull()){
            System.out.println("队列已满~");
            return false;
        }
        System.out.print("队列未满~");
        System.out.println(lastIndex);
        messages[lastIndex] = msg;
        lastIndex++;
        return true;
    }

    public static void main(String[] args) {
        Queue queue = new Queue(20);
        Order order = new Order(1020000L, System.currentTimeMillis(), "USD2CNY", 6.52d);
        queue.offer(new KmqMessage("test",null, order));
        System.out.println(queue.poll(111L,TimeUnit.MILLISECONDS));
        System.out.println(queue.poll(111L,TimeUnit.MILLISECONDS));
    }

}
